import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { observer } from 'mobx-react'
import { useStore } from '@renderer/store'
import { useEffect, useState } from 'react'
import { useLocation } from 'react-router-dom'
import qs from 'query-string'
import html2canvas from 'html2canvas'
import { Editor, Toolbar } from '@wangeditor/editor-for-react'

import { IconHome, IconMenu, IconSave, IconShareAlt } from '@arco-design/web-react/icon'
import { Link, useNavigate } from 'react-router-dom'
import { Button, Input, Message } from '@arco-design/web-react'


export function useQuery() {
  const { search } = useLocation()
  return (qs.parse(search))
}


function Note() {
  const { noteStore } = useStore()
  const navigate = useNavigate()
  const query = useQuery()
  const { id } = query

  const [noteDetail, setNoteDetail] = useState({})
  const [title, setTitle] = useState(undefined)
  // editor 实例
  const [editor, setEditor] = useState(null)

  // 编辑器内容
  const [html, setHtml] = useState('')
  // 工具栏配置
  const toolbarConfig = {}  // TS 语法
  // const toolbarConfig = { }                        // JS 语法

  // 编辑器配置
  const editorConfig = {    // TS 语法
    // const editorConfig = {                         // JS 语法
    placeholder: '请输入内容...'
  }

  useEffect(() => {
    let note = {}
    if (id) {
      note = noteStore.getNote(id)
      console.log('query', id, note)
      setTitle(note.title)

      setNoteDetail(note)
      setTimeout(() => {
        setHtml(note.detail)
      }, 100)
    }

  }, [id])

  // 及时销毁 editor ，重要！
  useEffect(() => {
    return () => {
      if (editor == null) return
      editor.destroy()
      setEditor(null)
    }
  }, [editor])

  const handleGoNote = (key) => {
    navigate('/home', { replace: true })
  }

  const handleSave = async () => {
    const contentDetail = editor.getHtml()
    if (!title && !contentDetail) {
      // Message.warning('note title')
      handleGoNote()
      return false
    }
    try {
      const picDom = document.getElementById('editorjs')
      const imageBase64 = await convertToImage(picDom)
      if (noteDetail.id) {
        noteStore.saveNote({
          ...noteDetail,
          title: title ? title : 'New note',
          detail: contentDetail,
          image: imageBase64
        }).then(res => {
          handleGoNote()
        })
      } else {
        noteStore.saveNote({
          title,
          detail: contentDetail,
          image: imageBase64,
          isBookmark: 0,
          isDelete: 0
        }).then(res => {
          handleGoNote()
        })
      }
    } catch (e) {
      Message.warning(e)
    }
  }

  const handleImage = () => {
    try {
      const picDom = document.getElementById('editorjs')
      convertToImage(picDom).then(res => {
        // console.log('笔记预览', res)
        // 将图片下载到本地
        var x = new XMLHttpRequest()
        x.open('GET', res, true)
        x.responseType = 'blob'
        x.onload = function(e) {
          var url = window.URL.createObjectURL(x.response)
          var a = document.createElement('a')
          a.href = url
          a.download = 'note preview'
          a.click()
        }
        x.send()
      })
    } catch (e) {

    }
  }

  // 功能：生成快照
  const convertToImage = (container, options = {}) => {
    // 1. 设置放大倍数
    const scale = window.devicePixelRatio
    // 2. 传入节点原始宽高
    const _width = container.offsetWidth
    const _height = container.offsetHeight
    // 3. html2canvas配置项
    const ops = {
      _width,
      _height,
      width: 1000,
      height: 800,
      useCORS: true,
      allowTaint: false,
      background: '#ffffff', // 一定要添加背景颜色，否则出来的图片，背景全部都是透明的
      scale: 2, // 处理模糊问题
      dpi: 300 // 处理模糊问题
    }
    return html2canvas(container, ops).then(canvas => {
      // 4. 返回图片的二进制数据
      return canvas.toDataURL('image/png')
    })
  }

  return <>
    <div className="page-edit">
      <div className="header">
        <div className="home">
          <Button icon={<IconHome />} onClick={handleSave}></Button>
        </div>
        <div className="ml-12 mr-12">
          <Button icon={<IconMenu />}></Button>
        </div>
        <Input value={title} onChange={(val) => setTitle(val)} allowClear placeholder="Notes title" />
        <div className="ml-12 mr-12">
          <Button type="primary" icon={<IconSave />} onClick={handleSave}></Button>
        </div>
        <div className="share">
          <Button icon={<IconShareAlt />} onClick={handleImage}></Button>
        </div>
      </div>
      <div className="editor-wrapper">
        <div class="edit-bar">
          <Toolbar
            editor={editor}
            defaultConfig={toolbarConfig}
            mode="default"
            style={{ borderBottom: '1px solid #ccc' }}
          />
        </div>
        <div className="editor" id="editorjs">
          <Editor
            defaultConfig={editorConfig}
            value={html}
            onCreated={setEditor}
            mode="default"
            style={{ minHeight: '500px', height: '100%' }}
          />
        </div>
      </div>
    </div>
  </>
}

export default observer(Note)
